#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
本地Web仪表板启动脚本
在本地机器上运行，连接虚拟机Redis服务
"""

import os
import sys
import subprocess
import time
from pathlib import Path

def check_dependencies():
    """检查本地依赖"""
    print("检查本地依赖...")
    
    required_packages = ['flask', 'redis', 'requests']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"✓ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"✗ {package} - 未安装")
    
    if missing_packages:
        print(f"\n需要安装以下包: {', '.join(missing_packages)}")
        print("请运行: pip install " + " ".join(missing_packages))
        return False
    
    return True

def check_vm_connectivity():
    """检查虚拟机连接性"""
    print("\n检查虚拟机连接性...")
    
    try:
        import redis
        from local_config import VM_CONFIG
        
        # 测试Redis连接
        r = redis.Redis(
            host=VM_CONFIG['redis_host'],
            port=VM_CONFIG['redis_port'],
            db=VM_CONFIG['redis_db'],
            password=VM_CONFIG['redis_password'],
            decode_responses=True,
            socket_timeout=5,
            socket_connect_timeout=5
        )
        r.ping()
        print(f"✓ Redis连接成功: {VM_CONFIG['redis_host']}:{VM_CONFIG['redis_port']}")
        return True
        
    except Exception as e:
        print(f"✗ Redis连接失败: {e}")
        print("请检查:")
        print("1. 虚拟机IP地址是否正确")
        print("2. Redis服务是否启动")
        print("3. 网络连接是否正常")
        print("4. Redis密码是否正确")
        return False

def start_local_web():
    """启动本地Web服务"""
    print("\n启动本地Web仪表板...")
    
    try:
        from local_config import LOCAL_CONFIG
        
        # 启动Web服务
        cmd = [
            sys.executable, 'local_web_dashboard.py',
            '--host', LOCAL_CONFIG['host'],
            '--port', str(LOCAL_CONFIG['port'])
        ]
        
        if LOCAL_CONFIG['debug']:
            cmd.append('--debug')
        
        print(f"启动命令: {' '.join(cmd)}")
        print(f"Web地址: http://localhost:{LOCAL_CONFIG['port']}")
        print("按 Ctrl+C 停止服务")
        
        subprocess.run(cmd)
        
    except KeyboardInterrupt:
        print("\n服务已停止")
    except Exception as e:
        print(f"启动失败: {e}")

def main():
    print("=" * 60)
    print("本地惠农网农产品价格监控Web仪表板")
    print("=" * 60)
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 检查虚拟机连接
    if not check_vm_connectivity():
        return
    
    # 启动Web服务
    start_local_web()

if __name__ == '__main__':
    main() 